/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.sequence;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Sequence;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.service.core.SequenceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.SequenceForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * <p>Prepares form bean to update sequence's data.
 * </p>
 * <p><a href="CallUpdateSequenceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.3 $ : 2007/12/17 13:38:25 $
 * @struts.action path="/core/sequence/callUpdate"
 * name="sequenceForm"
 * scope="request"
 * validate="false"
 * roles="core-sequence-update, core-sequence-updateOverriden, core-sequence-view"
 * @struts.action-forward name="updateSequence"
 * path=".core.sequence.update"
 * @struts.action-forward name="listSequences"
 * path="/core/sequence/list.do"
 * redirect="false"
 */
public final class CallUpdateSequenceAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		SequenceForm sequenceForm = (SequenceForm) form;

		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(sequenceForm.getOwnerId()) ) {
			ownerId = Long.valueOf(sequenceForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		if ( isCancelled(request) ) {
            return mapping.findForward("listSequences");
		}

        if (!request.isUserInRole("core-sequence-update") && !request.isUserInRole("core-sequence-updateOverriden")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
        }

		Long sequenceId;
		if ( !GenericValidator.isBlankOrNull(sequenceForm.getId()) ) {
			sequenceId = Long.valueOf(sequenceForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing sequence ID. Returning to list...");
			}
			return mapping.findForward("listSequences");
		}

		SequenceManager sequenceManager = (SequenceManager) getBean(Constants.SEQUENCE_MANAGER_BEAN);
		Sequence sequence = sequenceManager.retrieveSequence(sequenceId);
		if ( sequence == null ) {
			// sequence not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("sequenceNotFound", new ActionMessage("core.sequence.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listSequences");
		}

		WebappUtil.copyProperties(sequenceForm, sequence, request);

        String sequenceIdentifier = sequence.getIdentifier();

        LookupManager lookupManager = (LookupManager) getBean(Constants.LOOKUP_MANAGER_BEAN);
		Localizable owner = lookupManager.retrieveLocalizable(ownerId);

		if ( owner == null ) {
			ActionMessages errors = new ActionMessages();
			errors.add("ownerNotFound", new ActionMessage("core.sequence.errors.ownerNotFound"));
			saveErrors(request, errors);
			return mapping.findForward("admin");
		}

		boolean canCreateOrUpdate;
		Set identifiers = null;
        Set ownerIdentifiers = WebappUtil.getLocalizableSequenceIdentifiers(owner);
		if ( owner instanceof ContentPage || (owner instanceof ActionPage && !request.isUserInRole("core-sequence-update")) ) {
            // Updating overriden sequence
			if ( !request.isUserInRole("core-sequence-updateOverriden") ) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return null;
			}
			identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);
            identifiers.removeAll(ownerIdentifiers);
            identifiers.add(sequenceIdentifier);
			canCreateOrUpdate = identifiers != null && !identifiers.isEmpty() && identifiers.contains(sequenceIdentifier);
            List sortedIdentifiers;
            if (identifiers == null) {
                sortedIdentifiers = null;
            } else {
                sortedIdentifiers = new ArrayList(identifiers);
                Collections.sort(sortedIdentifiers);
            }
            request.getSession().setAttribute(WebappConstants.SEQUENCE_IDENTIFIERS_COLLECTION_KEY, sortedIdentifiers);
		} else if ( owner instanceof Layout && !request.isUserInRole("core-sequence-update") ) {
            // Updating overriden sequence
            boolean canUpdateOverriden = request.isUserInRole("core-sequence-updateOverriden");
			if ( !canUpdateOverriden ) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return null;
			}
			Layout ownerLayout = (Layout) owner;
            identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);
            identifiers.removeAll(ownerIdentifiers);
            identifiers.add(sequenceIdentifier);
			canCreateOrUpdate = identifiers != null && !identifiers.isEmpty();
			request.getSession().setAttribute(WebappConstants.SEQUENCE_IDENTIFIERS_COLLECTION_KEY, identifiers);
		} else {
            // (it's AP or Layout and user can update sequences) OR (its not CP,
            // AP or Layout)
			request.getSession().removeAttribute(WebappConstants.SEQUENCE_IDENTIFIERS_COLLECTION_KEY);
			if ( !request.isUserInRole("core-sequence-update") ) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return null;
			} else {
				canCreateOrUpdate = true;
			}
		}

		if ( !canCreateOrUpdate ) {
			ActionMessages errors = new ActionMessages();
			errors.add("cantCreateOrUpdate", new ActionMessage("core.sequence.errors.cantCreateOrUpdate"));
			saveErrors(request, errors);
			return mapping.findForward("listSequences");
		}

		String ownerInfo = WebappUtil.getLocalizableInfo(owner, request);
		request.getSession().setAttribute(WebappConstants.OWNER_INFO_KEY, ownerInfo);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("updateSequence");
	}

}